package com.yjh.server.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjh.common.other.BusinessException;
import com.yjh.common.utils.FileUploadUtil;
import com.yjh.pojo.dto.UpdatePswDto;
import com.yjh.pojo.dto.UserDto;
import com.yjh.pojo.entity.CourtCategory;
import com.yjh.pojo.entity.CourtInfo;
import com.yjh.pojo.entity.User;
import com.yjh.pojo.vo.R;
import com.yjh.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FileUploadUtil fileUploadUtil;

    @GetMapping("/page")
    public R<Page> getUserByPage(@RequestParam(value="current",defaultValue="1") Integer current, @RequestParam(value="pageSize",defaultValue="4") Integer pageSize,@RequestParam(value="role",defaultValue="0") Integer role){
        Page<User> page=new Page<>(current,pageSize);

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRole,role);

        userService.page(page,wrapper);
//        userService.page(page);

        return R.success(page);
    }

    @PutMapping("/update")
    @Transactional
    public R<String> update(@RequestBody UserDto userDto){
        if (userDto.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserId,userDto.getUserId());

        User user1 = userService.getOne(wrapper);
        user1.setUsername(userDto.getUsername());
        user1.setRole(userDto.getRole());
        user1.setAvatar(userDto.getAvatar());
        user1.setPhone(userDto.getPhone());
        user1.setState(userDto.getState());
//        System.out.println(user);
        userService.updateById(user1);
        return R.success("更新成功");
    }

    @PostMapping("/add")
    public R<String> add(@RequestBody UserDto userDto){
        User user=new User();
        BeanUtils.copyProperties(userDto,user);
        user.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));
        userService.save(user);
        return R.success("成功");
    }

    @DeleteMapping("/del")
    @Transactional
    public R<String> del(@RequestBody  List<Integer> ids){
        List<String> delUrls=new ArrayList<>();
        for(Integer id:ids){
            User user = userService.getById(id);
            System.out.println(user.getAvatar());
            String courtImg = user.getAvatar();
            delUrls.add(courtImg);
        }
        fileUploadUtil.deleteImgsByUrls(delUrls);
        userService.removeByIds(ids);
        return R.success("删除成功");
    }

    @GetMapping("/getOne")
    public R<User> getOne(@RequestParam("id") Integer id){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserId,id);

        User user = userService.getOne(wrapper);

        return R.success(user);

    }

    @PutMapping("/updatePsw")
    public R<String> updatePsw(@RequestBody UpdatePswDto updatePswDTO, HttpServletRequest request){
        String userId = (String) request.getAttribute("userId");

        if (userId == null) {
            return R.error("用户未登录或Token无效");
        }

        try {
            userService.updatePsw(updatePswDTO,userId);
            return R.success("密码修改成功");
        } catch (BusinessException e) {
            // 捕获业务异常（如原密码错误、用户不存在等）
            return R.error(e.getMessage());
        } catch (Exception e) {
            return R.error("密码修改失败");
        }
    }
}
